package openjdk.security;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by boot on 8/28/15.
 */
public class RSA {
    private String src = "I like raydoz";

    public static void main(String[] args) {

        RSA rsa = new RSA();
        rsa.jdkRSA();
    }

    public void jdkRSA() {
        try {
            // Get the init key
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(512);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            // exec sign
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PrivateKey pk = kf.generatePrivate(keySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(pk);
            signature.update(src.getBytes());
            byte[] bts = signature.sign();

            // verify

            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            kf = KeyFactory.getInstance("RSA");
            PublicKey publicKey = kf.generatePublic(x509EncodedKeySpec);
            Signature sign = Signature.getInstance("MD5withRSA");
            sign.initVerify(publicKey);
            sign.update(src.getBytes());
            boolean b = sign.verify(bts);

            System.out.println("jdk RSA verify:" + b);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
